/*
 * @Author: szx
 * @Date: 2021-12-05 14:48:47
 * @LastEditTime: 2021-12-05 15:20:47
 * @Description:
 * @FilePath: \leetcode\100-199\142\142.js
 */
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var detectCycle = function (head) {
    let fast = head;
    let slow = head;

    while (fast != null && fast.next != null) {
        if (fast == null || fast.next == null) {
            return null;
        }
        slow = slow.next;
        fast = fast.next.next;
        // 快慢指针相遇，此时从head 和 相遇点，同时查找直至相遇
        if (slow == fast) {
            let index1 = fast;
            let index2 = head;
            while (index1 != index2) {
                index1 = index1.next;
                index2 = index2.next;
            }
            return index2; // 返回环的入口
        }
    }
    return null;
};
